import { Injectable } from '@nestjs/common';
import { Member } from "../model/Member";
import { BaseService } from "./BaseService";
import * as MemberReq from '../model/req/MemberReq';
import { randomSix } from '../common/index'
import { Repository, SelectQueryBuilder, UpdateResult, ObjectLiteral } from "typeorm";
@Injectable()
export default class MemberService<T extends ObjectLiteral> extends BaseService<T> {
  constructor() {
    super(Member);
  }

  /**
     * @description: 根据id查找用户
     * @param {string} user_id
     * @return {*} 查找结果
     */
  async getUser(user_id: string): Promise<T | string> {
    const data = await this.repository.createQueryBuilder().where({ user_id }).getOne();
    return data ? data : "uid错误";
  }

  /**
   * @description: 根据mobileNo查找
   * @param {string} mobileNo
   * @return {object} 查找结果
   */
  async getMember(mobileNo: string): Promise<T | string> {
    const data = await this.repository.createQueryBuilder().where({ phonenumber: mobileNo }).getOne();
    return data ? data : "未找到该用户";
  }

  /**
   * @description: 登录
   * @param {MemberReq} data
   * @return {*}
   */
  async login(data: MemberReq.loginReq): Promise<T | string> {
    const userdata = await this.getMember(data.mobileNo);
    if (typeof userdata == 'string') {
      return userdata;
    }
    return userdata.password == data.password ? userdata : "密码错误";
  }

  /**
   * @description: 新增用户
   * @param {T} data 新用户数据
   * @return {Promise<T>} 新增的用户结果
   */
  async register(data: MemberReq.registerReq): Promise<T | string> {
    try {
      console.log("randomSix:", randomSix())
      const existing = await this.getMember(data.phoneData);
      if (typeof existing !== "string") {
        return `手机号${data.phoneData}已注册`;
      }
      const newMember: any = {
        phonenumber: data.phoneData,
        password: data.passData,
        spread_id: data.invData as number | undefined,
        nick_name: randomSix(6, '用户')
      };
      return await this.repository.save(newMember);
    } catch (err: any) {
      throw new Error(`新增用户失败：${err.message}`);
    }
  }

  /**
   * @description: 退出登录
   * @param {MemberReq} id
   * @return {*}
   */
  async logout(id: MemberReq._idReq): Promise<T | string> {
    const user: any = await this.getUser(id.user_id);
    if (typeof user != "string") {
      user.login_date = new Date();
      const data = await this.repository.save(user);
      return data
    }
    return user;
  }

  /**
   * @description: 修改密码
   * @param {MemberReq} data
   * @return {*}
   */
  async setPwd(data: MemberReq.setPwd): Promise<T | string> {
    const existingAccount: any = await this.getUser(data.user_id);
    // console.log(existingAccount)
    if (existingAccount && existingAccount.phonenumber == data.phoneData) {
      existingAccount.password = data.newPwd;
      return await this.repository.save(existingAccount);
    }
    return "用户信息有误";
  }


}